package cn.wolfcode.crm.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对controller的增强
 */
@ControllerAdvice
public class HandlerExceptionUtil {
    //针对不同的异常进行处理,权限异常

    //注解:对哪类异常进行处理
    @ExceptionHandler(UnauthorizedException.class)
    public void handlerException(HttpServletResponse response, HandlerMethod method) throws IOException {
        //判断是否有ajax请求 如果有直接就是返回json如果不是跳转界面 (错误信息/错误界面)
        ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
        if (annotation!= null) {
            //有注解
            response.setContentType("application/json;charset=UTF-8");
            //返回json数据
            response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult().mark("您没有权限执行该操作!")));
        }else{
            response.sendRedirect("/nopermission.jsp");
        }
    }
}
